#include "carSwitchController.h"
#include <btBulletDynamicsCommon.h>

bool carSwitchController::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
	if( !_carSwitch )
		return false;

// 	osg::Matrix matrix	= _model->getMatrix();
// 	osg::Vec3 tempTrans	= matrix.getTrans();

	btMotionState* carMotionState;
	btTransform tempCarWorldTrans;
	carMotionState	= _rbCar->getMotionState();
	carMotionState->getWorldTransform( tempCarWorldTrans );
	btVector3 tempCarTrans	= tempCarWorldTrans.getOrigin();
	btQuaternion tempCarRot	= tempCarWorldTrans.getRotation();

	switch( ea.getEventType() )
	{
	case (osgGA::GUIEventAdapter::KEYDOWN):
		  {
			  _carSwitch->setValue( 0, 1);
			  _carSwitch->setValue( 1, 0);
			  
			  switch( ea.getKey() )
			  {
			  case 'a':
			  case 'A':
			  case osgGA::GUIEventAdapter::KEY_Left:
				  {					  
					  tempCarWorldTrans.setRotation( btQuaternion( btVector3( 0, 0, 1), osg::DegreesToRadians(++(*_headingZ))) );
					  carMotionState->setWorldTransform( tempCarWorldTrans );
					  _rbCar->setMotionState( carMotionState );

					  break;
				  }
			  case 's':
			  case 'S':
			  case osgGA::GUIEventAdapter::KEY_Down:
				  {
					  tempCarWorldTrans.setOrigin( btVector3( tempCarTrans.x() - cos(osg::DegreesToRadians(90 + *_headingZ)),
						  tempCarTrans.y() - sin(osg::DegreesToRadians(90 + *_headingZ)),  tempCarTrans.z()) );
					  carMotionState->setWorldTransform( tempCarWorldTrans );
					  _rbCar->setMotionState( carMotionState );
					  break;
				  }
			  case 'd':
			  case 'D':
			  case osgGA::GUIEventAdapter::KEY_Right:
				  {
					  tempCarWorldTrans.setRotation( btQuaternion( btVector3( 0, 0, 1), osg::DegreesToRadians(--(*_headingZ))) );
					  carMotionState->setWorldTransform( tempCarWorldTrans );
					  _rbCar->setMotionState( carMotionState );
					  break;
				  }
			  case 'w':
			  case 'W':
			  case osgGA::GUIEventAdapter::KEY_Up:
				  {
					  tempCarWorldTrans.setOrigin( btVector3( tempCarTrans.x() + cos(osg::DegreesToRadians(90 + *_headingZ)),
						  tempCarTrans.y() + sin(osg::DegreesToRadians(90 + *_headingZ)),  tempCarTrans.z()) );
					  carMotionState->setWorldTransform( tempCarWorldTrans );
					  _rbCar->setMotionState( carMotionState );
					  break;
				  }
			  default:
				  break;
			  }
/*			  _model->setMatrix( matrix );*/
			  break;
		  }
	case (osgGA::GUIEventAdapter::KEYUP):
		  {
			  _carSwitch->setValue( 0, 0);
			  _carSwitch->setValue( 1, 1);
			  break;
		  }
	default:
		break;
	}
	return true;
}